import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import VueRouter from 'vue-router'

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
}

Vue.use(Router)

// export default new Router({
const routes = [
  {
    path: '/',
    redirect: "/Home"
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      activeNum: 0,
      isShowTabbar:true,
    },
    children: [
      {
        path: '/home/searchPopup',
        name: 'SearchPopup',
        component: () => import("@/views/SearchPopup.vue")
      }
    ]

  },
  // 专题导航栏
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      activeNum: 1,
      isShowTabbar:true,
    },
    component: () => import("@/views/Topic.vue")
  },
  // 分类导航栏
  {
    path: '/category',
    name: 'category',
    meta: {
      activeNum: 2,
      isShowTabbar:true,
    },
    component: () => import("@/views/Category.vue")
  },
  // 购物车导航栏
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      activeNum: 3,
      isShowTabbar:true,
    },
    component: () => import("@/views/Cart.vue")
  },
  // 我的导航栏
  {
    path: '/user',
    name: 'User',
    meta: {
      activeNum: 4,
      isShowTabbar:true,
    },
    component: () => import("@/views/User.vue")
  },
  // 商品详情
  {
    path: '/productDetail',
    name: 'ProductDetail',
    meta: {
      activeNum: 4
    },
    component: () => import("@/views/ProductDetail.vue")
  }
]
// })
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由拦截，路由守卫
router.beforeEach((to, from, next) => {
  // console.log("路由守卫......");
  // 要去往的路由对象
  // console.log(from);
  // 从哪里出发的路由对象
  // console.log(to);

  let token = localStorage.getItem("token");
  if (to.path == "/cart") {
    if (token) {
      // 放行
      next();
    }else{
      // 表示没有登录
      Vue.prototype.$toast("请先登录");
      setTimeout(()=>{
        console.log("***************");
        console.log(this);
        next("/user")//跳转到user路由
      },1000)
    }
  }
  next();//可以顺利通过要去的路由，如果不写next(),就不能访问到对应的路由
})

export default router
